//
//  SS_ChannelViewController.swift
//  SSNews
//
//  Created by 叶竞泽 on 2017/5/1.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit
import YYModel
import AXWebViewController
import MJRefresh

fileprivate let channelCellIdentifier = "channelCellIdentifier"

typealias ItemClickBlock = (UIViewController) -> ()

class SS_ChannelViewController: UIViewController {

    // MARK: - 属性
    
    var dataList: [NewsData]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    /// 控制器内容类型
    var type: String?
    
    /// 列表
    @IBOutlet var tableView: UITableView!
    
    // MARK: - 方法
    
    var block: ItemClickBlock?
    
    @objc fileprivate func loadData() {
        
        var params = ["key": newsAppKey]
        if type != nil {
            switch type! {
            case "top":
                params["type"] = "top"
            case "shehui":
                params["type"] = "shehui"
            case "guonei":
                params["type"] = "guonei"
            case "guoji":
                params["type"] = "guoji"
            case "yule":
                params["type"] = "yule"
            case "tiyu":
                params["type"] = "tiyu"
            case "junshi":
                params["type"] = "junshi"
            case "keji":
                params["type"] = "keji"
            case "caijing":
                params["type"] = "caijing"
            case "shishang":
                params["type"] = "shishang"
            default:
                break
            }
        }
        
        SS_Network.shared.request(method: .GET, urlString: newsAPI, parameters: params, progress: { (progress) in
        }, success: { (dataTask, json) in
            var dataList = json as? [String: Any]
            let result = dataList?["result"] as? [String: Any]
            let list = NewsResult.yy_model(with: result!)
            guard let arrList = list else {
                return
            }
            if self.dataList == nil {
                self.dataList = arrList.data
            } else {
                if arrList.data! != self.dataList! {
                    self.dataList = arrList.data
                }
            }
            self.tableView.mj_header.endRefreshing()
//                self.dataList = list?.data
            
        }) { (dataTask, error) in
            print(error)
        }
        
    }
    
    // MARK: - 生命周期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    deinit {
        print("deinit...\(type?.description ?? "")")
    }
}

// MARK: - 设置界面
extension SS_ChannelViewController {
    
    fileprivate func setupTableView() {
        tableView.register(UINib(nibName: "SS_ChannelCell", bundle: nil), forCellReuseIdentifier: channelCellIdentifier)
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, (navigationController?.navigationBar.bounds.height ?? 0) + (tabBarController?.tabBar.bounds.height ?? 0))
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
    }
    
    fileprivate func setupUI() {
        edgesForExtendedLayout = .top
        automaticallyAdjustsScrollViewInsets = false
        setupTableView()
    }
}
// MARK: - 数据源和代理
extension SS_ChannelViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if dataList == nil {
            return 1
        }
        return dataList!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: channelCellIdentifier, for: indexPath) as? SS_ChannelCell
        if dataList != nil {
            cell?.data = dataList?[indexPath.row]
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as? SS_ChannelCell
        guard let url = cell?.data?.url else {
            return
        }
        let webVC = AXWebViewController(address: url)
        block?(webVC)
    }
}
